import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {DatePicker} from 'antd';
import moment from 'moment';
import styles from './WrappedDatePicker.css';
import {formatMessage} from './localize';
const generateShowHourMinuteSecond = format =>
    // Ref: http://momentjs.com/docs/#/parsing/string-format/
    ({
        showHour: (
            format.indexOf('H') > -1 ||
            format.indexOf('h') > -1 ||
            format.indexOf('k') > -1
        ),
        showMinute: format.indexOf('m') > -1,
        showSecond: format.indexOf('s') > -1,
    })
    ;

class WrappedDatePicker extends PureComponent {
    onChange = date => {
        if(date)
            if(this.props.showTime)
                if(this.props.showTime.format) {
                    const timeOptions = generateShowHourMinuteSecond(this.props.showTime.format);
                    if(timeOptions.showMinute) {
                        this.props.onChange(date.startOf('minute').toISOString(), this.props.name);
                        return;
                    }
                    if(timeOptions.showHour) {
                        this.props.onChange(date.startOf('hour').toISOString(), this.props.name);
                        return;
                    }
                } else
                    this.props.onChange(date, this.props.name);
            else
                this.props.onChange(date.startOf('day').toISOString(), this.props.name);
        else
            this.props.onChange(null, this.props.name);
    }
    render() {
        const {name, onChange, value, ...rest} = this.props;
        let data = null;
        if(value && moment(value).isValid())
            data = moment(value);
        return (
            <DatePicker
                placeholder={formatMessage({
                    id: 'wrappedDatePicker.date',
                    defaultMessage: '请选择日期'
                })}
                className={styles.datePicker}
                value={data}
                onChange={this.onChange} {...rest} />
        );
    }
}

WrappedDatePicker.propTypes = {
    name: PropTypes.string,
    /** 增加时间选择功能*/
    showTime: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]),
    value: PropTypes.string,
    /**
     * @param value
     * @param name
     */
    onChange: PropTypes.func
};

export default WrappedDatePicker;
